const express = require('express');
const router = express.Router();

const OrderModel = require('../mongoModule/modules/OrderModel'); // 引入账单模型对象

const bodyParser = require('body-parser');
const urlencodedParser = bodyParser.urlencoded({ extended: false }); // 解析 querystring 格式请求体的中间件

// 用户账单
router.get('/order', function (req, res, next) {
    OrderModel.find({}).then(data => {
      res.render('list', { title: '账单列表', list: data });
    }, err => {
      // console.log('查询订单列表失败');
      res.render('result', { title: '查询订单列表失败', isSuccess: false });
    })
});

// 添加账单页
router.get('/order/create', function (req, res, next) {
  res.render('create', { title: '添加记录', data: {} });
});

// 创建账单接口
router.post('/order/create', urlencodedParser, function (req, res, next) {
  console.log('.body', req.body);
  const { orderText, orderDate, orderType, orderValue, orderDescription } = req.body;
    OrderModel.create({
      text: orderText,
      createTime: orderDate,
      type: orderType,
      moneyValue: orderValue,
      description: orderDescription
    }).then(
      (data) => {
        // console.log('保存成功');
        res.render('result', { title: '创建账单成功', isSuccess: true });
      },
      (err) => {
        // console.log('保存失败');
        res.render('result', { title: '创建账单失败', isSuccess: false });
      }
    );
});

// 删除账单接口
router.get('/order/delete/:id',  (req, res) => {
  let id = req.params.id
  OrderModel.deleteOne({ _id: id }).then(data => {
    res.render('result', { title: '删除账单成功', isSuccess: true });
  }, err => {
    res.status(500).render('result', { title: '删除账单失败', isSuccess: false });
  })
})

// 前往更新账单页面
router.get('/order/:id', (req, res) => {
  let id = req.params.id
  OrderModel.findOne({ _id: id }).then(data => {
    res.render('create', { title: '更新记录', data: data });
  }, err => {
    res.status(500).render('result', { title: '查询账单详细信息失败', isSuccess: false });
  })
})

// 更新账单数据
router.post('/order/update/:id',  (req, res) => {
  console.log('更新', req.body);
  let id = req.params.id
  const { orderText, orderDate, orderType, orderValue, orderDescription } = req.body;
  OrderModel.updateOne({ _id: id }, {
    text: orderText,
    createTime: orderDate,
    type: orderType,
    moneyValue: orderValue,
    description: orderDescription
  }).then(data => {
    res.render('result', { title: '更新账单成功', isSuccess: true });
  }, err => {
    res.status(500).render('result', { title: '更新账单失败', isSuccess: false });
  })
})

module.exports = router;
